"""
Copyright 2012 Wieser Dietmar, Margit Mutschlechner.

This file is part of Multimedia Social Networking Platform.

Multimedia Social Networking Platform is free software: 
you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Multimedia Social Networking Platform is distributed
in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Multimedia Social Networking Platform.  
If not, see <http://www.gnu.org/licenses/>.

"""

from msnp.service.network import NetworkController
from msnp.service.network.sending import Sender
from threading import Timer
from msnp.logger import Logger

#the timer instance
__resendTimer = None
#the timer interval
__timerInterval = 5.0
#queue for function calls 
__callQueue = []


#################
## START_TIMER ##
#################

def startResendTimer():
    """This function starts the resend timer."""
    
    global __timerInterval
    global __resendTimer
    __resendTimer = Timer(__timerInterval, __executeOpenCalls)
    __resendTimer.start()
        
        
################
## STOP_TIMER ##
################

def stopResendTimer():
    """This function stops the resend timer."""
    
    global __resendTimer
    print "stop resend timer"
    if __resendTimer != None:
        __resendTimer.cancel()
        
        
####################
## TIMER_FINISHED ##
####################
        
def __executeOpenCalls():
    """This method is executed when the resend timer is finished.
    
    It goes through the callQueue, calls every item and removes it from the queue.
    Then the timer will be started again."""
    
    global __callQueue
    successor = NetworkController.getMySelf().getSuccessor()
    
    if successor == None:
        successor = NetworkController.getMySelf().getMyIdentity()
        
    for item in __callQueue:
        Logger.info("send again " + item[0].__name__)
        
        if len(item) == 1:
            if item[0] == Sender.superPeerAbilityTest:
                item[0]()
        
        elif len(item) == 2:
            if item[0] == Sender.logoutLowLevelPeer:
                item[0](item[1])
                
        elif len(item) == 3:
            if item[0] == Sender.hello:
                item[0](item[1], item[2])
                
        elif len(item) == 4:
            if item[0] == Sender.authenticate:
                item[0](item[1], item[2], item[3])
            elif item[0] == Sender.backupCallback:
                item[0](item[1], item[2], item[3])
            elif item[0] == Sender.sendRTMessageErrorCallback:
                item[0](item[1], item[2], item[3])
                
        elif len(item) == 5:
            if item[0] == Sender.callbackCrashBroadcast:
                item[0](item[1], item[2], item[3], item[4])
            elif item[0] == Sender.sendReconnectRing:
                item[0](item[1], item[2], item[3], item[4])
            elif item[0] == Sender.forwardResponsibilityCallForAuth:
                item[0](item[1], item[2], item[3], item[4])
                
        elif len(item) == 6:
            if item[0] == Sender.callbackResponsibleIdentityForAuth:
                item[0](item[1], item[2], item[3], item[4], item[5])
            elif item[0] == Sender.callbackResponsibleIdentityForFinger:
                item[0](item[1], item[2], item[3], item[4], item[5])
            elif item[0] == Sender.addMember:
                item[0](item[1], item[2], item[3], item[4], item[5])
            elif item[0] == Sender.forwardResponsibilityCall:
                item[0](item[1], item[2], item[3], item[4], item[5])

        elif len(item) == 7:
            if item[0] == Sender.forwardRingReport:
                item[0](item[1], item[2], item[3], item[4], item[5], item[6])
            elif item[0] == Sender.callbackGroups:
                item[0](item[1], item[2], item[3], item[4], item[5], item[6])
            elif item[0] == Sender.forwardPersonalMessage:
                item[0](item[1], item[2], item[3], item[4], item[5], item[6])
            elif item[0] == Sender.callbackPersonalMessage:
                item[0](item[1], item[2], item[3], item[4], item[5], item[6])
            elif item[0] == Sender.pollMediaContentSinceLastSynch:
                item[0](item[1], item[2], item[3], item[4], item[5], item[6])
                
        elif len(item) == 8:
            if item[0] == Sender.setMemberStatus:
                item[0](item[1], item[2], item[3], item[4], item[5], item[6], item[7])
            elif item[0] == Sender.callbackResponsibleIdentity:
                item[0](item[1], item[2], item[3], item[4], item[5], item[6], item[7])
        
        elif len(item) == 9:
            if item[0] == Sender.callbackMemberStatusChanged:
                item[0](item[1], item[2], item[3], item[4], item[5], item[6], item[7], item[8])
            elif item[0] == Sender.getGroupsWithOwner:
                item[0](item[1], item[2], item[3], item[4], item[5], item[6], item[7], item[8])
            elif item[0] == Sender.getGroupsWithoutOwner:
                item[0](item[1], item[2], item[3], item[4], item[5], item[6], item[7], item[8])
                
        else:
            Logger.info("error, function in queue not handled!!!!")
            
        __callQueue.remove(item)
        
    #timer has to be started again
    startResendTimer()


################
## CALL_QUEUE ##
################
        
def addCall(item):
    """This function adds the given item to the queue.
    
    Args:
        item: the function to be called again.
    """
    
    global __callQueue
    
    __callQueue.append(item)

